<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Smart Memories Collector</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
            margin: 0;
            padding: 20px;
            max-width: 600px;
            margin: 0 auto;
            color: #333;
        }
        h1 {
            font-size: 1.8rem;
            color: #2c3e50;
            margin-bottom: 1rem;
        }
        .container {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }
        textarea {
            width: 100%;
            height: 200px;
            padding: 12px;
            border: 1px solid #ccc;
            border-radius: 8px;
            font-size: 16px;
            resize: vertical;
        }
        button {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 15px;
            font-size: 16px;
            border-radius: 8px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #45a049;
        }
        button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        .status-container {
            margin-top: 20px;
        }
        .status {
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 5px;
        }
        .success {
            background-color: #dff0d8;
            color: #3c763d;
        }
        .error {
            background-color: #f2dede;
            color: #a94442;
        }
        .loading {
            background-color: #d9edf7;
            color: #31708f;
        }
        .memory-item {
            padding: 10px;
            background-color: #f8f9fa;
            border-radius: 4px;
            margin-bottom: 15px;
            border-left: 4px solid #4CAF50;
        }
        .memory-error {
            border-left-color: #d9534f;
        }
        .badge {
            display: inline-block;
            padding: 3px 7px;
            font-size: 12px;
            border-radius: 10px;
            margin-left: 5px;
            background-color: #6c757d;
            color: white;
        }
        .badge-success {
            background-color: #28a745;
        }
        .badge-danger {
            background-color: #dc3545;
        }
        .loading-spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(0, 0, 0, 0.1);
            border-radius: 50%;
            border-top-color: #4CAF50;
            animation: spin 1s ease-in-out infinite;
            margin-right: 10px;
        }
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        .user-info {
            background-color: #f0f8ff;
            padding: 10px 15px;
            border-radius: 8px;
            margin: 15px 0;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border: 1px solid #bedcf9;
        }
        .user-info .label {
            font-weight: bold;
            color: #0056b3;
        }
        .warning-box {
            background-color: #fff3cd;
            color: #856404;
            border-left: 4px solid #ffeeba;
            padding: 15px;
            margin: 15px 0;
            border-radius: 0 4px 4px 0;
            display: none;
        }
    </style>
</head>
<body>
    <h1>Smart Memories Collector</h1>
    
    <div class="user-info" id="user-info">
        <span><span class="label">User ID:</span> <span id="current-uid">Not set</span></span>
        <button id="change-uid-btn" style="padding: 5px 10px; font-size: 0.8rem;">Change</button>
    </div>
    
    <div class="warning-box" id="no-uid-warning">
        <strong>No User ID detected!</strong> Please add ?uid=YOUR_USER_ID to the URL to use this application.
    </div>
    
    <div class="container">
        <p>Enter your notes, learnings, or insights in any format. The system will create coherent memories that preserve context.</p>
        <textarea id="user-text" placeholder="Enter your notes in any format:

MrBeast 
- burn the boats
- If you don't know smth, do it 100 times
- Uses random word generator for ideas

Made to stick 
- People would guess a "tap" from song only in 2% of cases
- People would rather wait for result than do an action
- Sun exposure is bad and unhealthy"></textarea>
        <button id="submit-btn">Extract & Submit Memories</button>
    </div>
    
    <div class="status-container" id="status-container"></div>
    <div id="memories-container"></div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const textArea = document.getElementById('user-text');
            const submitBtn = document.getElementById('submit-btn');
            const statusContainer = document.getElementById('status-container');
            const memoriesContainer = document.getElementById('memories-container');
            const currentUidElement = document.getElementById('current-uid');
            const noUidWarning = document.getElementById('no-uid-warning');
            const changeUidBtn = document.getElementById('change-uid-btn');
            
            // Function to get URL parameters
            function getUrlParameter(name) {
                name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
                const regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
                const results = regex.exec(location.search);
                return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
            }
            
            // Get uid from URL
            let userId = getUrlParameter('uid');
            
            // Update the UI to show current UID or warning
            if (userId) {
                currentUidElement.textContent = userId;
                noUidWarning.style.display = 'none';
                submitBtn.disabled = false;
            } else {
                currentUidElement.textContent = 'Not set';
                noUidWarning.style.display = 'block';
                submitBtn.disabled = true;
            }
            
            // Add event listener for changing UID
            changeUidBtn.addEventListener('click', function() {
                const newUid = prompt('Enter your User ID:', userId || '');
                if (newUid) {
                    // Update the URL with the new UID
                    const url = new URL(window.location);
                    url.searchParams.set('uid', newUid);
                    window.history.replaceState({}, '', url);
                    
                    // Update the UI
                    userId = newUid;
                    currentUidElement.textContent = userId;
                    noUidWarning.style.display = 'none';
                    submitBtn.disabled = false;
                }
            });

            submitBtn.addEventListener('click', async function() {
                const text = textArea.value.trim();
                
                if (!userId) {
                    showStatus('Please provide a User ID by adding ?uid=YOUR_USER_ID to the URL.', 'error');
                    return;
                }
                
                if (!text) {
                    showStatus('Please enter some text.', 'error');
                    return;
                }
                
                // Disable the button during processing
                submitBtn.disabled = true;
                showStatus(`<div class="loading-spinner"></div> Processing your text...`, 'loading');
                
                // We'll now just send the raw text and let the server handle extraction
                const memories = [text];
                
                try {
                    const response = await fetch('/submit-memories', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ 
                            memories: memories,
                            use_ai: true,
                            uid: userId  // Include the user ID in the request
                        })
                    });
                    
                    const result = await response.json();
                    
                    if (result.success) {
                        const time = result.processing_time || ''; 
                        
                        showStatus(`
                            <strong>Success!</strong> ${result.message}
                            ${time ? `<div>Processing time: ${time}</div>` : ''}
                        `, 'success');
                        
                        displayResults(result.results);
                    } else {
                        showStatus(`Error: ${result.error}`, 'error');
                    }
                } catch (error) {
                    showStatus(`Error: ${error.message}`, 'error');
                }
                
                // Re-enable the button
                submitBtn.disabled = false;
            });
            
            function displayResults(results) {
                memoriesContainer.innerHTML = '<h3>Extracted Memories:</h3>';
                
                results.forEach((result, index) => {
                    const memoryElement = document.createElement('div');
                    memoryElement.className = `memory-item ${result.success ? '' : 'memory-error'}`;
                    
                    const badge = document.createElement('span');
                    badge.className = result.success ? 'badge badge-success' : 'badge badge-danger';
                    badge.textContent = result.success ? 'Success' : 'Failed';
                    
                    // Create a div for the memory number and text
                    const memoryTextElement = document.createElement('div');
                    memoryTextElement.innerHTML = `<strong>Memory #${index + 1}:</strong> ${result.memory}`;
                    
                    memoryElement.appendChild(memoryTextElement);
                    memoryElement.appendChild(badge);
                    
                    if (!result.success && result.error) {
                        const errorMsg = document.createElement('div');
                        errorMsg.style.fontSize = '0.8rem';
                        errorMsg.style.marginTop = '5px';
                        errorMsg.style.color = '#d9534f';
                        errorMsg.textContent = `Error: ${result.error}`;
                        memoryElement.appendChild(errorMsg);
                    }
                    
                    memoriesContainer.appendChild(memoryElement);
                });
            }
            
            function showStatus(message, type) {
                const statusDiv = document.createElement('div');
                statusDiv.className = `status ${type}`;
                statusDiv.innerHTML = message;
                
                // Clear previous status messages
                statusContainer.innerHTML = '';
                statusContainer.appendChild(statusDiv);
            }
        });
    </script>
</body>
</html> 